package com.xwj.redpacket.service.impl;

import com.xwj.redpacket.dao.RedDetailMapper;
import com.xwj.redpacket.dao.RedRecordMapper;
import com.xwj.redpacket.dao.RedWarRecordMapper;
import com.xwj.redpacket.domain.RedDetail;
import com.xwj.redpacket.domain.RedRecord;
import com.xwj.redpacket.domain.RedWarRecord;
import com.xwj.redpacket.dto.RedPacketDto;
import com.xwj.redpacket.service.RedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xwj
 * @date 2020/4/27
 */
@Service
public class RedServiceImpl implements RedService {
    @Autowired
    private RedRecordMapper redRecordMapper;
    @Autowired
    private RedDetailMapper redDetailMapper;
    @Autowired
    private RedWarRecordMapper redWarRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void recordRedPacket(RedPacketDto redPacketDto, String redId, List<Integer> redPacketList) {
        RedRecord redRecord = new RedRecord();
        redRecord.setUserId(redPacketDto.getUserId());
        redRecord.setActive(true);
        redRecord.setRedPacket(redId);
        redRecord.setTotal(redPacketDto.getTotal());
        redRecord.setAmount(BigDecimal.valueOf(redPacketDto.getAmount()));
        redRecord.setCreateTime(LocalDateTime.now());
        redRecordMapper.insertSelective(redRecord);
        List<RedDetail> redDetails = new ArrayList<>(redPacketList.size());
        RedDetail redDetail;
        for (Integer amount : redPacketList) {
            redDetail = new RedDetail();
            redDetail.setRedRecordId(redRecord.getId());
            redDetail.setAmount(BigDecimal.valueOf(amount));
            redDetail.setActive(true);
            redDetail.setCreateTime(LocalDateTime.now());
            redDetails.add(redDetail);
        }
        redDetailMapper.batchInsert(redDetails);
    }

    @Override
    public void saveRedWarRecord(Long userId, String redId, BigDecimal amount) {
        RedWarRecord redWarRecord = new RedWarRecord();
        redWarRecord.setAmount(amount);
        redWarRecord.setUserId(userId);
        redWarRecord.setRedPacket(redId);
        redWarRecord.setCreateTime(LocalDateTime.now());
        redWarRecord.setActive(true);
        redWarRecordMapper.insertSelective(redWarRecord);
    }
}
